package com.blankii.androidlibrary.lib.permission

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.Settings
import androidx.core.app.ActivityCompat.startActivityForResult
import androidx.fragment.app.FragmentActivity
import com.permissionx.guolindev.PermissionX


/**
 * author: lenovo
 * created on: 2023/12/18 15:13
 * description:
 */
object PermissionManager {
    fun requestPermissions(
        context: FragmentActivity, listener: PermissionResultListener, vararg permissions: String
    ) {
        var result = true
        permissions.forEach {
            if (!PermissionX.isGranted(context, it)) {
                result = false
                return@forEach
            }
        }
        if (!result) {
            PermissionX.init(context).permissions(
                *permissions
            ).onExplainRequestReason { scope, deniedList ->

            }.request { allGranted, grantedList, deniedList ->
                if (allGranted) {
                    listener.success()
                } else {
                    listener.failure()
                }
            }
        } else {
            listener.success()
        }
    }

    fun requestManageExternalStoragePermission(activity: Activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // 先判断有没有权限
            if (Environment.isExternalStorageManager()) {

            } else {
                val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION)
                intent.setData(Uri.parse("package:" + activity.packageName))
                startActivityForResult(activity, intent, 1, null)
            }
        }
    }
}